/*
 * Copyright (c) 2007 Compl Yue Still, All Rights Reserved.
 */

package hbi.wire.as3.host
{
	import flash.utils.IDataInput;

	public class TypedArrayContent implements DataTag
	{
		
		public function get tagValue():*
		{
			return values;
		}
		
		public function reset():void
		{
			values = new Array();
			length = -1;
		}
		
		private var componentReceiver:DataTag;
		
		public function TypedArrayContent(dimension:int, elementReceiver:DataTag)
		{
			if(dimension > 1)
				componentReceiver = new TypedArrayContent(dimension-1, elementReceiver);
			else
				componentReceiver = elementReceiver;
		}
		
		private var values:Array = new Array();
		
		private var length:int = -1;
		
		public function processIncomingData(input:IDataInput):Boolean
		{
			if(length < 0) // length not read yet
			{
				if(input.bytesAvailable < 4) // length not yet available
					return false;
				length = input.readInt();
				if(length < 0) throw new Error("Too large array!");
				if(length < 1) return true;
			}
			
			tag_scan: while(input.bytesAvailable > 0)
			{
				if(componentReceiver.processIncomingData(input))
				{
					values.push(componentReceiver.tagValue);
					componentReceiver.reset();
					if(values.length >= length)
						return true;
				}
				else
				{
					break tag_scan;
				}
			}
			
			return false;
		}
		
	}
}
